import fs from 'fs'
import archiver from 'archiver'
import { fileSizeFormat } from './tools'

const dirPath = 'zip'
// 创建文件夹
if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath)
}

export default function packaging (pathList) {
    return new Promise((resolve, reject) => {
        const dirList = fs.readdirSync(dirPath)
        const zipName = `images-${dirList.length + 1}.zip`
        const zipPath = `${dirPath}/${zipName}`
        const output = fs.createWriteStream(zipPath)

        const archive = archiver('zip', {
            zlib: { level: 9 }
        })

        // 对文件进行压缩
        pathList.forEach(item=>{
            archive.append(fs.createReadStream(item), { 'name': item })
        })

        // 将打包对象与输出流关联
        archive.pipe(output)

        // 监听所有 archiver 数据都写完
        output.on('close', function() {
            resolve(zipName)
            console.log('打包文件路径', zipPath)
            console.log('打包文件大小', fileSizeFormat(archive.pointer()))

            // 删除 pathList
            deleteTempFile(pathList)
        })
        archive.on('error', function(err) {
            reject(err)
        })
        // 打包
        archive.finalize()
    })
}

// 删除临时文件
function deleteTempFile (pathList) {
    pathList.forEach(path => {
        fs.unlink(path, (err) => {
            if (err) {
                console.error(err)
            }

            deleteComplete()
        })
    })

    function deleteComplete () {
        deleteComplete.number++

        if (deleteComplete.number === pathList.length) {
            console.log('临时文件已删除')
        }
    }
    deleteComplete.number = 0
}
